<?php

/**
 * NOTICE OF LICENSE
 *
 * THIS SOURCE FILE IS PART OF EVEBIT'S PRIVATE PROJECT.
 * 
 * DO NOT USE THIS FILE IN OTHER PLACE.
 *
 * @category    EveBit_Library
 * @package     Application
 * @author      Cheng Wei <berlios.o@gmail.com>
 * @version     $$Id: Auth.php 674 2011-05-05 09:26:11Z cheng.wei $$
 * @copyright   Copyright (c) 2008 Evebit Inc. China (http://www.evebit.com)
 */

/**
 * @see Zend_Application_Resource_ResourceAbstract
 */
require_once 'Zend/Application/Resource/ResourceAbstract.php';

require_once 'Zend/Auth.php';

require_once 'Zend/Auth/Storage/Exception.php';
/**
 * Resource for settings auth options
 *
 * @uses      Zend_Application_Resource_ResourceAbstract
 * 
 * @category    EveBit_Library
 * @package     Application
 * @copyright   Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license   http://framework.zend.com/license/new-bsd     New BSD License
 */
class Evebit_Application_Resource_Auth extends Zend_Application_Resource_ResourceAbstract {
	
	protected $storage;
	
	protected $adapter;
	
	/**
	 * Defined by Zend_Application_Resource_Resource
	 *
	 * @return Zend_View
	 */
	public function init() {
		$options = $this->getOptions();
		
		Zend_Auth::getInstance()->setStorage($this->getStorage());
		
		return $this;
	}
	
	/**
	 * Get storage for auth
	 * 
	 * @return Evebit_Auth_Storage_Default
	 */
	public function getStorage() {
		if (!$this->storage) {
			$options = $this->getOptions();
			
			$storageClass = isset($options['storage']) ? $options['storage'] : 'Evebit_Auth_Storage_Default';
			$modelClass = isset($options['model']) ? $options['model'] : null;
			
			if (!class_exists($storageClass)) {
				throw new Zend_Auth_Storage_Exception("Storage class '$storageClass' invalid");
			}
			
			$storage = new $storageClass($options);
			if (!is_a($storage, 'Zend_Auth_Storage_Interface')) {
				throw new Zend_Auth_Storage_Exception("Storage class '$storageClass' invalid");
			}
			
			if ($modelClass) {
				$storage->setModelTypeClass($modelClass);
			}
			$this->storage = $storage;
		}
		
		return $this->storage;
	}
	
	/**
	 * @return Evebit_Auth_Adapter_Default
	 */
	public function getAdapter() {
		if (!$this->adapter) {
			$options = $this->getOptions();
			$adapterClass = isset($options['adapter']) ? $options['adapter'] : 'Evebit_Auth_Adapter_Default';
			$modelClass = isset($options['model']) ? $options['model'] : null;
			
			if (!class_exists($adapterClass)) {
				throw new Zend_Auth_Storage_Exception("Storage class '$adapterClass' invalid");
			}
			
			$adapter = new $adapterClass($options);
			if (!is_a($adapter, 'Evebit_Auth_Adapter_Default')) {
				throw new Zend_Auth_Storage_Exception("Storage class '$adapterClass' invalid");
			}
			
			if ($modelClass) {
				$adapter->setModelTypeClass($modelClass);
			}
			$this->adapter = $adapter;
		}
		
		return $this->adapter;
	}

}
